package persistence;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import model.Midia;

public class MidiaDaoImpl implements MidiaDao {
	Connection c;

	public MidiaDaoImpl() {
		GenericDao gDao = new GenericDao();
		c = gDao.getConnection();
	}

	@Override
	public void salvaMidia(Midia midia) throws SQLException {
		String sql = "INSERT INTO midias VALUES (?,?)";
		PreparedStatement ps = c.prepareStatement(sql);

		ps.setInt(1, midia.getIdMidia());
		ps.setString(2, midia.getNomeMidia());

		ps.execute();
		ps.close();

	}

	@Override
	public void editaMidia(Midia midia) throws SQLException {
		String sql = "UPDATE midias SET nomeMidia = ? WHERE idMidia = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setString(1, midia.getNomeMidia());
		ps.setInt(2, midia.getIdMidia());
		ps.execute();
		ps.close();

	}

	@Override
	public void excluiMidia(Midia midia) throws SQLException {
		String sql = "DELETE midias WHERE idMidia = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setInt(1, midia.getIdMidia());
		ps.execute();
		ps.close();

	}

	@Override
	public Midia pesquisaMidia(Midia midia) throws SQLException {
		Midia m = new Midia();
		String sql = "SELECT idMidia, nomeMidia FROM midias WHERE idMidia = ?";
		PreparedStatement ps = c.prepareStatement(sql);
		ps.setInt(1, midia.getIdMidia());
		ResultSet rs = ps.executeQuery();
		if (rs.next()) {

			m.setIdMidia(rs.getInt("idMidia"));
			m.setNomeMidia(rs.getString("nomeMidia"));

		}
		ps.close();
		rs.close();
		return m;
	}
}
